#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Log.hpp"
#include "Err.hpp"

static const int backlog = 32;
static const int defaultsock = -1;

class Sock
{
public:
    Sock(int listensock = defaultsock)
        : _listensock(listensock)
    {
    }
    ~Sock()
    {
        if (_listensock != defaultsock)
            close(_listensock);
    }

public:
    // 1. 创建socket文件套接字对象
    void Socket()
    {
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            logMessage(FATAL, "socket create error");
            exit(SOCKET_ERR);
        }
        logMessage(NORMAL, "socket create success: %d", _listensock);

        int opt = 1;
        setsockopt(_listensock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof opt);
    }

    // 2.bind自己的网络信息
    void Bind(const uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof local);

        local.sin_family = AF_INET;
        local.sin_addr.s_addr = INADDR_ANY;
        local.sin_port = htons(port);

        int n = bind(_listensock, (struct sockaddr *)&local, sizeof local);
        if (n < 0)
        {
            logMessage(FATAL, "socket bind error");
            exit(BIND_ERR);
        }
        logMessage(NORMAL, "socket bind success");
    }

    // 3. 设置socket 为监听状态
    void Listen()
    {
        int n = listen(_listensock, backlog);
        if (n < 0)
        {
            logMessage(FATAL, "socket listen error");
            exit(LISTEN_ERR);
        }
        logMessage(NORMAL, "socket listen success");
    }

    int Accept(std::string *clientip, uint16_t *clientport, int *err)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int sock = accept(_listensock, (struct sockaddr *)&peer, &len);
        *err = errno;
        if (sock < 0)
        {
            logMessage(ERROR, "socket accept error,next");
        }
        else
        {
            logMessage(NORMAL, "accept a new link success, get a new sock: %d", sock);
            *clientip = inet_ntoa(peer.sin_addr);
            *clientport = ntohs(peer.sin_port);
        }

        return sock;
    }

    int Fd()
    {
        return _listensock;
    }

    void Close()
    {
        if (_listensock != defaultsock)
            close(_listensock);
    }

private:
    int _listensock;
};